import Fetch from '@wattjs/network'
import { message } from 'ant-design-vue'
import { APP_ID, BASE_URL, XSRF_HEADER, REQUEST_TIMEOUT } from './config'
import { ll } from '../utils'
import Bus from '../bus'

const http = new Fetch({
  config: {
    APP_ID,
    BASE_URL,
    XSRF_HEADER,
    REQUEST_TIMEOUT
  },
  transformRequest: [(data, headers) => {
    const token = ll.get('token')
    if (token) Object.assign(headers, {
      'Authorization': `Bearer ${token}`
    })
    return data
  }],
  transformResponse: [(data = {}, headers) => {
    const { code, notify, msg } = typeof data === 'string' && data.indexOf('{') > -1 ? JSON.parse(data) : data
    if (code === 110 || code === 101) {
      ll.remove('token')
      ll.remove('op_id')
      ll.remove('op_name')
      // 跳转到登录页面
      Bus.emit('logout')
    }
    if (notify && msg) {
      message.success(msg)
    }
    return data
  }],
  // withCredentials: true,
  showToast: (content) => {
    if (typeof content !== 'string') content = JSON.stringify(content)
    // 错误提示
    message.error({
      content,
      duration: 2.5
    })
  },
})

export default http
